3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
19 * @ingroup Maintenance
20 * @defgroup Maintenance Maintenance
23 // Bail on old versions of PHP, or if composer has not been run yet to install
25 require_once __DIR__
. '/../includes/PHPVersionCheck.php';
26 wfEntryPointCheck( 'cli' );
28 use MediaWiki\Shell\Shell
;
29 use Wikimedia\Rdbms\DBReplicationWaitError
;
32 * @defgroup MaintenanceArchive Maintenance archives
33 * @ingroup Maintenance
36 // Define this so scripts can easily find doMaintenance.php
37 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__
. '/doMaintenance.php' );
38 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN
); // original name, harmless
42 use Wikimedia\Rdbms\IDatabase
;
43 use MediaWiki\Logger\LoggerFactory
;
44 use MediaWiki\MediaWikiServices
;
45 use Wikimedia\Rdbms\LBFactory
;
46 use Wikimedia\Rdbms\IMaintainableDatabase
;
49 * Abstract maintenance class for quickly writing and churning out
50 * maintenance scripts with minimal effort. All that _must_ be defined
51 * is the execute() method. See docs/maintenance.txt for more info
52 * and a quick demo of how to use it.
55 * @ingroup Maintenance
57 abstract class Maintenance
{
59 * Constants for DB access type
60 * @see Maintenance::getDbType()
66 // Const for getStdin()
67 const STDIN_ALL
= 'all';
69 // This is the desired params
70 protected $mParams = [];
72 // Array of mapping short parameters to long ones
73 protected $mShortParamsMap = [];
75 // Array of desired args
76 protected $mArgList = [];
78 // This is the list of options that were actually passed
79 protected $mOptions = [];
81 // This is the list of arguments that were actually passed
82 protected $mArgs = [];
84 // Name of the script currently running
87 // Special vars for params that are always used
88 protected $mQuiet = false;
89 protected $mDbUser, $mDbPass;
91 // A description of the script, children should change this via addDescription()
92 protected $mDescription = '';
94 // Have we already loaded our user input?
95 protected $mInputLoaded = false;
98 * Batch size. If a script supports this, they should set
99 * a default with setBatchSize()
103 protected $mBatchSize = null;
105 // Generic options added by addDefaultParams()
106 private $mGenericParameters = [];
107 // Generic options which might or not be supported by the script
108 private $mDependantParameters = [];
111 * Used by getDB() / setDB()
112 * @var IMaintainableDatabase
116 /** @var float UNIX timestamp */
117 private $lastReplicationWait = 0.0;
120 * Used when creating separate schema files.
126 * Accessible via getConfig()
133 * @see Maintenance::requireExtension
136 private $requiredExtensions = [];
139 * Used to read the options in the order they were passed.
140 * Useful for option chaining (Ex. dumpBackup.php). It will
141 * be an empty array if the options are passed in through
142 * loadParamsAndArgs( $self, $opts, $args ).
144 * This is an array of arrays where
145 * 0 => the option and 1 => parameter value.
149 public $orderedOptions = [];
152 * Default constructor. Children should call this *first* if implementing
153 * their own constructors
155 public function __construct() {
156 // Setup $IP, using MW_INSTALL_PATH if it exists
158 $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
159 ?
getenv( 'MW_INSTALL_PATH' )
160 : realpath( __DIR__
. '/..' );
162 $this->addDefaultParams();
163 register_shutdown_function( [ $this, 'outputChanneled' ], false );
167 * Should we execute the maintenance script, or just allow it to be included
168 * as a standalone class? It checks that the call stack only includes this
169 * function and "requires" (meaning was called from the file scope)
173 public static function shouldExecute() {
174 global $wgCommandLineMode;
176 if ( !function_exists( 'debug_backtrace' ) ) {
177 // If someone has a better idea...
178 return $wgCommandLineMode;
181 $bt = debug_backtrace();
182 $count = count( $bt );
184 return false; // sanity
186 if ( $bt[0]['class'] !== self
::class ||
$bt[0]['function'] !== 'shouldExecute' ) {
187 return false; // last call should be to this function
189 $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
190 for ( $i = 1; $i < $count; $i++
) {
191 if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
192 return false; // previous calls should all be "requires"
200 * Do the actual work. All child classes will need to implement this
202 abstract public function execute();
205 * Add a parameter to the script. Will be displayed on --help
206 * with the associated description
208 * @param string $name The name of the param (help, version, etc)
209 * @param string $description The description of the param to show on --help
210 * @param bool $required Is the param required?
211 * @param bool $withArg Is an argument required with this option?
212 * @param string|bool $shortName Character to use as short name
213 * @param bool $multiOccurrence Can this option be passed multiple times?
215 protected function addOption( $name, $description, $required = false,
216 $withArg = false, $shortName = false, $multiOccurrence = false
218 $this->mParams
[$name] = [
219 'desc' => $description,
220 'require' => $required,
221 'withArg' => $withArg,
222 'shortName' => $shortName,
223 'multiOccurrence' => $multiOccurrence
226 if ( $shortName !== false ) {
227 $this->mShortParamsMap
[$shortName] = $name;
232 * Checks to see if a particular param exists.
233 * @param string $name The name of the param
236 protected function hasOption( $name ) {
237 return isset( $this->mOptions
[$name] );
241 * Get an option, or return the default.
243 * If the option was added to support multiple occurrences,
244 * this will return an array.
246 * @param string $name The name of the param
247 * @param mixed $default Anything you want, default null
250 protected function getOption( $name, $default = null ) {
251 if ( $this->hasOption( $name ) ) {
252 return $this->mOptions
[$name];
254 // Set it so we don't have to provide the default again
255 $this->mOptions
[$name] = $default;
257 return $this->mOptions
[$name];
262 * Add some args that are needed
263 * @param string $arg Name of the arg, like 'start'
264 * @param string $description Short description of the arg
265 * @param bool $required Is this required?
267 protected function addArg( $arg, $description, $required = true ) {
268 $this->mArgList
[] = [
270 'desc' => $description,
271 'require' => $required
276 * Remove an option. Useful for removing options that won't be used in your script.
277 * @param string $name The option to remove.
279 protected function deleteOption( $name ) {
280 unset( $this->mParams
[$name] );
284 * Set the description text.
285 * @param string $text The text of the description
287 protected function addDescription( $text ) {
288 $this->mDescription
= $text;
292 * Does a given argument exist?
293 * @param int $argId The integer value (from zero) for the arg
296 protected function hasArg( $argId = 0 ) {
297 return isset( $this->mArgs
[$argId] );
302 * @param int $argId The integer value (from zero) for the arg
303 * @param mixed $default The default if it doesn't exist
306 protected function getArg( $argId = 0, $default = null ) {
307 return $this->hasArg( $argId ) ?
$this->mArgs
[$argId] : $default;
317 protected function getBatchSize() {
318 return $this->mBatchSize
;
322 * Set the batch size.
323 * @param int $s The number of operations to do in a batch
325 protected function setBatchSize( $s = 0 ) {
326 $this->mBatchSize
= $s;
328 // If we support $mBatchSize, show the option.
329 // Used to be in addDefaultParams, but in order for that to
330 // work, subclasses would have to call this function in the constructor
331 // before they called parent::__construct which is just weird
332 // (and really wasn't done).
333 if ( $this->mBatchSize
) {
334 $this->addOption( 'batch-size', 'Run this many operations ' .
335 'per batch, default: ' . $this->mBatchSize
, false, true );
336 if ( isset( $this->mParams
['batch-size'] ) ) {
337 // This seems a little ugly...
338 $this->mDependantParameters
['batch-size'] = $this->mParams
['batch-size'];
344 * Get the script's name
347 public function getName() {
352 * Return input from stdin.
353 * @param int $len The number of bytes to read. If null, just return the handle.
354 * Maintenance::STDIN_ALL returns the full length
357 protected function getStdin( $len = null ) {
358 if ( $len == self
::STDIN_ALL
) {
359 return file_get_contents( 'php://stdin' );
361 $f = fopen( 'php://stdin', 'rt' );
365 $input = fgets( $f, $len );
368 return rtrim( $input );
374 public function isQuiet() {
375 return $this->mQuiet
;
379 * Throw some output to the user. Scripts can call this with no fears,
380 * as we handle all --quiet stuff here
381 * @param string $out The text to show to the user
382 * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
384 protected function output( $out, $channel = null ) {
385 // This is sometimes called very early, before Setup.php is included.
386 if ( class_exists( MediaWikiServices
::class ) ) {
387 // Try to periodically flush buffered metrics to avoid OOMs
388 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
389 if ( $stats->getDataCount() > 1000 ) {
390 MediaWiki
::emitBufferedStatsdData( $stats, $this->getConfig() );
394 if ( $this->mQuiet
) {
397 if ( $channel === null ) {
398 $this->cleanupChanneled();
401 $out = preg_replace( '/\n\z/', '', $out );
402 $this->outputChanneled( $out, $channel );
407 * Throw an error to the user. Doesn't respect --quiet, so don't use
408 * this for non-error output
409 * @param string $err The error to display
410 * @param int $die Deprecated since 1.31, use Maintenance::fatalError() instead
412 protected function error( $err, $die = 0 ) {
413 if ( intval( $die ) !== 0 ) {
414 wfDeprecated( __METHOD__
. '( $err, $die )', '1.31' );
415 $this->fatalError( $err, intval( $die ) );
417 $this->outputChanneled( false );
419 ( PHP_SAPI
== 'cli' || PHP_SAPI
== 'phpdbg' ) &&
420 !defined( 'MW_PHPUNIT_TEST' )
422 fwrite( STDERR
, $err . "\n" );
429 * Output a message and terminate the current script.
431 * @param string $msg Error message
432 * @param int $exitCode PHP exit status. Should be in range 1-254.
435 protected function fatalError( $msg, $exitCode = 1 ) {
436 $this->error( $msg );
440 private $atLineStart = true;
441 private $lastChannel = null;
444 * Clean up channeled output. Output a newline if necessary.
446 public function cleanupChanneled() {
447 if ( !$this->atLineStart
) {
449 $this->atLineStart
= true;
454 * Message outputter with channeled message support. Messages on the
455 * same channel are concatenated, but any intervening messages in another
456 * channel start a new line.
457 * @param string $msg The message without trailing newline
458 * @param string $channel Channel identifier or null for no
459 * channel. Channel comparison uses ===.
461 public function outputChanneled( $msg, $channel = null ) {
462 if ( $msg === false ) {
463 $this->cleanupChanneled();
468 // End the current line if necessary
469 if ( !$this->atLineStart
&& $channel !== $this->lastChannel
) {
475 $this->atLineStart
= false;
476 if ( $channel === null ) {
477 // For unchanneled messages, output trailing newline immediately
479 $this->atLineStart
= true;
481 $this->lastChannel
= $channel;
485 * Does the script need different DB access? By default, we give Maintenance
486 * scripts normal rights to the DB. Sometimes, a script needs admin rights
487 * access for a reason and sometimes they want no access. Subclasses should
488 * override and return one of the following values, as needed:
489 * Maintenance::DB_NONE - For no DB access at all
490 * Maintenance::DB_STD - For normal DB access, default
491 * Maintenance::DB_ADMIN - For admin DB access
494 public function getDbType() {
499 * Add the default parameters to the scripts
501 protected function addDefaultParams() {
502 # Generic (non script dependant) options:
504 $this->addOption( 'help', 'Display this help message', false, false, 'h' );
505 $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
506 $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
507 $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
508 $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
511 'Set a specific memory limit for the script, '
512 . '"max" for no limit or "default" to avoid changing it'
514 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
515 "http://en.wikipedia.org. This is sometimes necessary because " .
516 "server name detection may fail in command line scripts.", false, true );
517 $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
518 // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
519 $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, true );
521 # Save generic options to display them separately in help
522 $this->mGenericParameters
= $this->mParams
;
524 # Script dependant options:
526 // If we support a DB, show the options
527 if ( $this->getDbType() > 0 ) {
528 $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
529 $this->addOption( 'dbpass', 'The password to use for this script', false, true );
532 # Save additional script dependant options to display
533 # Â them separately in help
534 $this->mDependantParameters
= array_diff_key( $this->mParams
, $this->mGenericParameters
);
541 public function getConfig() {
542 if ( $this->config
=== null ) {
543 $this->config
= MediaWikiServices
::getInstance()->getMainConfig();
546 return $this->config
;
551 * @param Config $config
553 public function setConfig( Config
$config ) {
554 $this->config
= $config;
558 * Indicate that the specified extension must be
559 * loaded before the script can run.
561 * This *must* be called in the constructor.
564 * @param string $name
566 protected function requireExtension( $name ) {
567 $this->requiredExtensions
[] = $name;
571 * Verify that the required extensions are installed
575 public function checkRequiredExtensions() {
576 $registry = ExtensionRegistry
::getInstance();
578 foreach ( $this->requiredExtensions
as $name ) {
579 if ( !$registry->isLoaded( $name ) ) {
585 $joined = implode( ', ', $missing );
586 $msg = "The following extensions are required to be installed "
587 . "for this script to run: $joined. Please enable them and then try again.";
588 $this->fatalError( $msg );
593 * Set triggers like when to try to run deferred updates
596 public function setAgentAndTriggers() {
597 if ( function_exists( 'posix_getpwuid' ) ) {
598 $agent = posix_getpwuid( posix_geteuid() )['name'];
602 $agent .= '@' . wfHostname();
604 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
605 // Add a comment for easy SHOW PROCESSLIST interpretation
606 $lbFactory->setAgentName(
607 mb_strlen( $agent ) > 15 ?
mb_substr( $agent, 0, 15 ) . '...' : $agent
609 self
::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
613 * @param LBFactory $LBFactory
614 * @param Config $config
617 public static function setLBFactoryTriggers( LBFactory
$LBFactory, Config
$config ) {
618 $services = MediaWikiServices
::getInstance();
619 $stats = $services->getStatsdDataFactory();
620 // Hook into period lag checks which often happen in long-running scripts
621 $lbFactory = $services->getDBLoadBalancerFactory();
622 $lbFactory->setWaitForReplicationListener(
624 function () use ( $stats, $config ) {
625 // Check config in case of JobRunner and unit tests
626 if ( $config->get( 'CommandLineMode' ) ) {
627 DeferredUpdates
::tryOpportunisticExecute( 'run' );
629 // Try to periodically flush buffered metrics to avoid OOMs
630 MediaWiki
::emitBufferedStatsdData( $stats, $config );
633 // Check for other windows to run them. A script may read or do a few writes
634 // to the master but mostly be writing to something else, like a file store.
635 $lbFactory->getMainLB()->setTransactionListener(
637 function ( $trigger ) use ( $stats, $config ) {
638 // Check config in case of JobRunner and unit tests
639 if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase
::TRIGGER_COMMIT
) {
640 DeferredUpdates
::tryOpportunisticExecute( 'run' );
642 // Try to periodically flush buffered metrics to avoid OOMs
643 MediaWiki
::emitBufferedStatsdData( $stats, $config );
649 * Run a child maintenance script. Pass all of the current arguments
651 * @param string $maintClass A name of a child maintenance class
652 * @param string $classFile Full path of where the child is
653 * @return Maintenance
655 public function runChild( $maintClass, $classFile = null ) {
656 // Make sure the class is loaded first
657 if ( !class_exists( $maintClass ) ) {
659 require_once $classFile;
661 if ( !class_exists( $maintClass ) ) {
662 $this->error( "Cannot spawn child: $maintClass" );
667 * @var $child Maintenance
669 $child = new $maintClass();
670 $child->loadParamsAndArgs( $this->mSelf
, $this->mOptions
, $this->mArgs
);
671 if ( !is_null( $this->mDb
) ) {
672 $child->setDB( $this->mDb
);
679 * Do some sanity checking and basic setup
681 public function setup() {
682 global $IP, $wgCommandLineMode;
684 # Abort if called from a web server
685 # wfIsCLI() is not available yet
686 if ( PHP_SAPI
!== 'cli' && PHP_SAPI
!== 'phpdbg' ) {
687 $this->fatalError( 'This script must be run from the command line' );
690 if ( $IP === null ) {
691 $this->fatalError( "\$IP not set, aborting!\n" .
692 '(Did you forget to call parent::__construct() in your maintenance script?)' );
695 # Make sure we can handle script parameters
696 if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
697 $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
700 // Send PHP warnings and errors to stderr instead of stdout.
701 // This aids in diagnosing problems, while keeping messages
702 // out of redirected output.
703 if ( ini_get( 'display_errors' ) ) {
704 ini_set( 'display_errors', 'stderr' );
707 $this->loadParamsAndArgs();
710 # Set the memory limit
711 # Note we need to set it again later in cache LocalSettings changed it
712 $this->adjustMemoryLimit();
714 # Set max execution time to 0 (no limit). PHP.net says that
715 # "When running PHP from the command line the default setting is 0."
716 # But sometimes this doesn't seem to be the case.
717 ini_set( 'max_execution_time', 0 );
719 # Define us as being in MediaWiki
720 define( 'MEDIAWIKI', true );
722 $wgCommandLineMode = true;
724 # Turn off output buffering if it's on
725 while ( ob_get_level() > 0 ) {
729 $this->validateParamsAndArgs();
733 * Normally we disable the memory_limit when running admin scripts.
734 * Some scripts may wish to actually set a limit, however, to avoid
735 * blowing up unexpectedly. We also support a --memory-limit option,
736 * to allow sysadmins to explicitly set one if they'd prefer to override
737 * defaults (or for people using Suhosin which yells at you for trying
738 * to disable the limits)
741 public function memoryLimit() {
742 $limit = $this->getOption( 'memory-limit', 'max' );
743 $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
748 * Adjusts PHP's memory limit to better suit our needs, if needed.
750 protected function adjustMemoryLimit() {
751 $limit = $this->memoryLimit();
752 if ( $limit == 'max' ) {
753 $limit = -1; // no memory limit
755 if ( $limit != 'default' ) {
756 ini_set( 'memory_limit', $limit );
761 * Activate the profiler (assuming $wgProfiler is set)
763 protected function activateProfiler() {
764 global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
766 $output = $this->getOption( 'profiler' );
771 if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
772 $class = $wgProfiler['class'];
773 /** @var Profiler $profiler */
774 $profiler = new $class(
775 [ 'sampling' => 1, 'output' => [ $output ] ]
777 +
[ 'threshold' => $wgProfileLimit ]
779 $profiler->setTemplated( true );
780 Profiler
::replaceStubInstance( $profiler );
783 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
784 $trxProfiler->setLogger( LoggerFactory
::getInstance( 'DBPerformance' ) );
785 $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__
);
789 * Clear all params and arguments.
791 public function clearParamsAndArgs() {
792 $this->mOptions
= [];
794 $this->mInputLoaded
= false;
798 * Load params and arguments from a given array
799 * of command-line arguments
804 public function loadWithArgv( $argv ) {
807 $this->orderedOptions
= [];
810 for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
811 if ( $arg == '--' ) {
812 # End of options, remainder should be considered arguments
813 $arg = next( $argv );
814 while ( $arg !== false ) {
816 $arg = next( $argv );
819 } elseif ( substr( $arg, 0, 2 ) == '--' ) {
821 $option = substr( $arg, 2 );
822 if ( isset( $this->mParams
[$option] ) && $this->mParams
[$option]['withArg'] ) {
823 $param = next( $argv );
824 if ( $param === false ) {
825 $this->error( "\nERROR: $option parameter needs a value after it\n" );
826 $this->maybeHelp( true );
829 $this->setParam( $options, $option, $param );
831 $bits = explode( '=', $option, 2 );
832 if ( count( $bits ) > 1 ) {
839 $this->setParam( $options, $option, $param );
841 } elseif ( $arg == '-' ) {
842 # Lonely "-", often used to indicate stdin or stdout.
844 } elseif ( substr( $arg, 0, 1 ) == '-' ) {
846 $argLength = strlen( $arg );
847 for ( $p = 1; $p < $argLength; $p++
) {
849 if ( !isset( $this->mParams
[$option] ) && isset( $this->mShortParamsMap
[$option] ) ) {
850 $option = $this->mShortParamsMap
[$option];
853 if ( isset( $this->mParams
[$option]['withArg'] ) && $this->mParams
[$option]['withArg'] ) {
854 $param = next( $argv );
855 if ( $param === false ) {
856 $this->error( "\nERROR: $option parameter needs a value after it\n" );
857 $this->maybeHelp( true );
859 $this->setParam( $options, $option, $param );
861 $this->setParam( $options, $option, 1 );
869 $this->mOptions
= $options;
870 $this->mArgs
= $args;
871 $this->loadSpecialVars();
872 $this->mInputLoaded
= true;
876 * Helper function used solely by loadParamsAndArgs
877 * to prevent code duplication
879 * This sets the param in the options array based on
880 * whether or not it can be specified multiple times.
883 * @param array $options
884 * @param string $option
885 * @param mixed $value
887 private function setParam( &$options, $option, $value ) {
888 $this->orderedOptions
[] = [ $option, $value ];
890 if ( isset( $this->mParams
[$option] ) ) {
891 $multi = $this->mParams
[$option]['multiOccurrence'];
895 $exists = array_key_exists( $option, $options );
896 if ( $multi && $exists ) {
897 $options[$option][] = $value;
898 } elseif ( $multi ) {
899 $options[$option] = [ $value ];
900 } elseif ( !$exists ) {
901 $options[$option] = $value;
903 $this->error( "\nERROR: $option parameter given twice\n" );
904 $this->maybeHelp( true );
909 * Process command line arguments
910 * $mOptions becomes an array with keys set to the option names
911 * $mArgs becomes a zero-based array containing the non-option arguments
913 * @param string $self The name of the script, if any
914 * @param array $opts An array of options, in form of key=>value
915 * @param array $args An array of command line arguments
917 public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
918 # If we were given opts or args, set those and return early
920 $this->mSelf
= $self;
921 $this->mInputLoaded
= true;
924 $this->mOptions
= $opts;
925 $this->mInputLoaded
= true;
928 $this->mArgs
= $args;
929 $this->mInputLoaded
= true;
932 # If we've already loaded input (either by user values or from $argv)
933 # skip on loading it again. The array_shift() will corrupt values if
934 # it's run again and again
935 if ( $this->mInputLoaded
) {
936 $this->loadSpecialVars();
942 $this->mSelf
= $argv[0];
943 $this->loadWithArgv( array_slice( $argv, 1 ) );
947 * Run some validation checks on the params, etc
949 protected function validateParamsAndArgs() {
951 # Check to make sure we've got all the required options
952 foreach ( $this->mParams
as $opt => $info ) {
953 if ( $info['require'] && !$this->hasOption( $opt ) ) {
954 $this->error( "Param $opt required!" );
959 foreach ( $this->mArgList
as $k => $info ) {
960 if ( $info['require'] && !$this->hasArg( $k ) ) {
961 $this->error( 'Argument <' . $info['name'] . '> required!' );
967 $this->maybeHelp( true );
972 * Handle the special variables that are global to all scripts
974 protected function loadSpecialVars() {
975 if ( $this->hasOption( 'dbuser' ) ) {
976 $this->mDbUser
= $this->getOption( 'dbuser' );
978 if ( $this->hasOption( 'dbpass' ) ) {
979 $this->mDbPass
= $this->getOption( 'dbpass' );
981 if ( $this->hasOption( 'quiet' ) ) {
982 $this->mQuiet
= true;
984 if ( $this->hasOption( 'batch-size' ) ) {
985 $this->mBatchSize
= intval( $this->getOption( 'batch-size' ) );
990 * Maybe show the help.
991 * @param bool $force Whether to force the help to show, default false
993 protected function maybeHelp( $force = false ) {
994 if ( !$force && !$this->hasOption( 'help' ) ) {
998 $screenWidth = 80; // TODO: Calculate this!
1000 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1002 ksort( $this->mParams
);
1003 $this->mQuiet
= false;
1006 if ( $this->mDescription
) {
1007 $this->output( "\n" . wordwrap( $this->mDescription
, $screenWidth ) . "\n" );
1009 $output = "\nUsage: php " . basename( $this->mSelf
);
1011 // ... append parameters ...
1012 if ( $this->mParams
) {
1013 $output .= " [--" . implode( "|--", array_keys( $this->mParams
) ) . "]";
1016 // ... and append arguments.
1017 if ( $this->mArgList
) {
1019 foreach ( $this->mArgList
as $k => $arg ) {
1020 if ( $arg['require'] ) {
1021 $output .= '<' . $arg['name'] . '>';
1023 $output .= '[' . $arg['name'] . ']';
1025 if ( $k < count( $this->mArgList
) - 1 ) {
1030 $this->output( "$output\n\n" );
1032 # TODO abstract some repetitive code below
1034 // Generic parameters
1035 $this->output( "Generic maintenance parameters:\n" );
1036 foreach ( $this->mGenericParameters
as $par => $info ) {
1037 if ( $info['shortName'] !== false ) {
1038 $par .= " (-{$info['shortName']})";
1041 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1042 "\n$tab$tab" ) . "\n"
1045 $this->output( "\n" );
1047 $scriptDependantParams = $this->mDependantParameters
;
1048 if ( count( $scriptDependantParams ) > 0 ) {
1049 $this->output( "Script dependant parameters:\n" );
1050 // Parameters description
1051 foreach ( $scriptDependantParams as $par => $info ) {
1052 if ( $info['shortName'] !== false ) {
1053 $par .= " (-{$info['shortName']})";
1056 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1057 "\n$tab$tab" ) . "\n"
1060 $this->output( "\n" );
1063 // Script specific parameters not defined on construction by
1064 // Maintenance::addDefaultParams()
1065 $scriptSpecificParams = array_diff_key(
1066 # all script parameters:
1068 # remove the Maintenance default parameters:
1069 $this->mGenericParameters
,
1070 $this->mDependantParameters
1072 if ( count( $scriptSpecificParams ) > 0 ) {
1073 $this->output( "Script specific parameters:\n" );
1074 // Parameters description
1075 foreach ( $scriptSpecificParams as $par => $info ) {
1076 if ( $info['shortName'] !== false ) {
1077 $par .= " (-{$info['shortName']})";
1080 wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1081 "\n$tab$tab" ) . "\n"
1084 $this->output( "\n" );
1088 if ( count( $this->mArgList
) > 0 ) {
1089 $this->output( "Arguments:\n" );
1090 // Arguments description
1091 foreach ( $this->mArgList
as $info ) {
1092 $openChar = $info['require'] ?
'<' : '[';
1093 $closeChar = $info['require'] ?
'>' : ']';
1095 wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1096 $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1099 $this->output( "\n" );
1106 * Handle some last-minute setup here.
1108 public function finalSetup() {
1109 global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
1110 global $wgDBadminuser, $wgDBadminpassword;
1111 global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
1113 # Turn off output buffering again, it might have been turned on in the settings files
1114 if ( ob_get_level() ) {
1118 $wgCommandLineMode = true;
1120 # Override $wgServer
1121 if ( $this->hasOption( 'server' ) ) {
1122 $wgServer = $this->getOption( 'server', $wgServer );
1125 # If these were passed, use them
1126 if ( $this->mDbUser
) {
1127 $wgDBadminuser = $this->mDbUser
;
1129 if ( $this->mDbPass
) {
1130 $wgDBadminpassword = $this->mDbPass
;
1133 if ( $this->getDbType() == self
::DB_ADMIN
&& isset( $wgDBadminuser ) ) {
1134 $wgDBuser = $wgDBadminuser;
1135 $wgDBpassword = $wgDBadminpassword;
1137 if ( $wgDBservers ) {
1139 * @var $wgDBservers array
1141 foreach ( $wgDBservers as $i => $server ) {
1142 $wgDBservers[$i]['user'] = $wgDBuser;
1143 $wgDBservers[$i]['password'] = $wgDBpassword;
1146 if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1147 $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1148 $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1150 MediaWikiServices
::getInstance()->getDBLoadBalancerFactory()->destroy();
1153 # Apply debug settings
1154 if ( $this->hasOption( 'mwdebug' ) ) {
1155 require __DIR__
. '/../includes/DevelopmentSettings.php';
1158 // Per-script profiling; useful for debugging
1159 $this->activateProfiler();
1161 $this->afterFinalSetup();
1163 $wgShowSQLErrors = true;
1165 Wikimedia\
suppressWarnings();
1166 set_time_limit( 0 );
1167 Wikimedia\restoreWarnings
();
1169 $this->adjustMemoryLimit();
1173 * Execute a callback function at the end of initialisation
1175 protected function afterFinalSetup() {
1176 if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1177 call_user_func( MW_CMDLINE_CALLBACK
);
1182 * Potentially debug globals. Originally a feature only
1185 public function globals() {
1186 if ( $this->hasOption( 'globals' ) ) {
1187 print_r( $GLOBALS );
1192 * Generic setup for most installs. Returns the location of LocalSettings
1195 public function loadSettings() {
1196 global $wgCommandLineMode, $IP;
1198 if ( isset( $this->mOptions
['conf'] ) ) {
1199 $settingsFile = $this->mOptions
['conf'];
1200 } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1201 $settingsFile = MW_CONFIG_FILE
;
1203 $settingsFile = "$IP/LocalSettings.php";
1205 if ( isset( $this->mOptions
['wiki'] ) ) {
1206 $bits = explode( '-', $this->mOptions
['wiki'] );
1207 if ( count( $bits ) == 1 ) {
1210 define( 'MW_DB', $bits[0] );
1211 define( 'MW_PREFIX', $bits[1] );
1214 if ( !is_readable( $settingsFile ) ) {
1215 $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1216 "must exist and be readable in the source directory.\n" .
1217 "Use --conf to specify it." );
1219 if ( isset( $this->mOptions
['server'] ) ) {
1220 $_SERVER['SERVER_NAME'] = $this->mOptions
['server'];
1222 $wgCommandLineMode = true;
1224 return $settingsFile;
1228 * Support function for cleaning up redundant text records
1229 * @param bool $delete Whether or not to actually delete the records
1230 * @author Rob Church <robchur@gmail.com>
1232 public function purgeRedundantText( $delete = true ) {
1233 # Data should come off the master, wrapped in a transaction
1234 $dbw = $this->getDB( DB_MASTER
);
1235 $this->beginTransaction( $dbw, __METHOD__
);
1237 # Get "active" text records from the revisions table
1239 $this->output( 'Searching for active text records in revisions table...' );
1240 $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1241 foreach ( $res as $row ) {
1242 $cur[] = $row->rev_text_id
;
1244 $this->output( "done.\n" );
1246 # Get "active" text records from the archive table
1247 $this->output( 'Searching for active text records in archive table...' );
1248 $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__
, [ 'DISTINCT' ] );
1249 foreach ( $res as $row ) {
1250 # old pre-MW 1.5 records can have null ar_text_id's.
1251 if ( $row->ar_text_id
!== null ) {
1252 $cur[] = $row->ar_text_id
;
1255 $this->output( "done.\n" );
1257 # Get the IDs of all text records not in these sets
1258 $this->output( 'Searching for inactive text records...' );
1259 $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1260 $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__
, [ 'DISTINCT' ] );
1262 foreach ( $res as $row ) {
1263 $old[] = $row->old_id
;
1265 $this->output( "done.\n" );
1267 # Inform the user of what we're going to do
1268 $count = count( $old );
1269 $this->output( "$count inactive items found.\n" );
1271 # Delete as appropriate
1272 if ( $delete && $count ) {
1273 $this->output( 'Deleting...' );
1274 $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__
);
1275 $this->output( "done.\n" );
1279 $this->commitTransaction( $dbw, __METHOD__
);
1283 * Get the maintenance directory.
1286 protected function getDir() {
1291 * Returns a database to be used by current maintenance script. It can be set by setDB().
1292 * If not set, wfGetDB() will be used.
1293 * This function has the same parameters as wfGetDB()
1295 * @param int $db DB index (DB_REPLICA/DB_MASTER)
1296 * @param string|string[] $groups default: empty array
1297 * @param string|bool $wiki default: current wiki
1298 * @return IMaintainableDatabase
1300 protected function getDB( $db, $groups = [], $wiki = false ) {
1301 if ( is_null( $this->mDb
) ) {
1302 return wfGetDB( $db, $groups, $wiki );
1309 * Sets database object to be returned by getDB().
1311 * @param IDatabase $db
1313 public function setDB( IDatabase
$db ) {
1318 * Begin a transcation on a DB
1320 * This method makes it clear that begin() is called from a maintenance script,
1321 * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
1323 * @param IDatabase $dbw
1324 * @param string $fname Caller name
1327 protected function beginTransaction( IDatabase
$dbw, $fname ) {
1328 $dbw->begin( $fname );
1332 * Commit the transcation on a DB handle and wait for replica DBs to catch up
1334 * This method makes it clear that commit() is called from a maintenance script,
1335 * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
1337 * @param IDatabase $dbw
1338 * @param string $fname Caller name
1339 * @return bool Whether the replica DB wait succeeded
1342 protected function commitTransaction( IDatabase
$dbw, $fname ) {
1343 $dbw->commit( $fname );
1345 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
1346 $lbFactory->waitForReplication(
1347 [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait
]
1349 $this->lastReplicationWait
= microtime( true );
1352 } catch ( DBReplicationWaitError
$e ) {
1358 * Rollback the transcation on a DB handle
1360 * This method makes it clear that rollback() is called from a maintenance script,
1361 * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
1363 * @param IDatabase $dbw
1364 * @param string $fname Caller name
1367 protected function rollbackTransaction( IDatabase
$dbw, $fname ) {
1368 $dbw->rollback( $fname );
1372 * Lock the search index
1373 * @param IMaintainableDatabase &$db
1375 private function lockSearchindex( $db ) {
1376 $write = [ 'searchindex' ];
1386 $db->lockTables( $read, $write, __CLASS__
. '::' . __METHOD__
);
1391 * @param IMaintainableDatabase &$db
1393 private function unlockSearchindex( $db ) {
1394 $db->unlockTables( __CLASS__
. '::' . __METHOD__
);
1398 * Unlock and lock again
1399 * Since the lock is low-priority, queued reads will be able to complete
1400 * @param IMaintainableDatabase &$db
1402 private function relockSearchindex( $db ) {
1403 $this->unlockSearchindex( $db );
1404 $this->lockSearchindex( $db );
1408 * Perform a search index update with locking
1409 * @param int $maxLockTime The maximum time to keep the search index locked.
1410 * @param string $callback The function that will update the function.
1411 * @param IMaintainableDatabase $dbw
1412 * @param array $results
1414 public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1418 if ( $maxLockTime ) {
1419 $this->output( " --- Waiting for lock ---" );
1420 $this->lockSearchindex( $dbw );
1422 $this->output( "\n" );
1425 # Loop through the results and do a search update
1426 foreach ( $results as $row ) {
1427 # Allow reads to be processed
1428 if ( $maxLockTime && time() > $lockTime +
$maxLockTime ) {
1429 $this->output( " --- Relocking ---" );
1430 $this->relockSearchindex( $dbw );
1432 $this->output( "\n" );
1434 call_user_func( $callback, $dbw, $row );
1437 # Unlock searchindex
1438 if ( $maxLockTime ) {
1439 $this->output( " --- Unlocking --" );
1440 $this->unlockSearchindex( $dbw );
1441 $this->output( "\n" );
1446 * Update the searchindex table for a given pageid
1447 * @param IDatabase $dbw A database write handle
1448 * @param int $pageId The page ID to update.
1449 * @return null|string
1451 public function updateSearchIndexForPage( $dbw, $pageId ) {
1452 // Get current revision
1453 $rev = Revision
::loadFromPageId( $dbw, $pageId );
1456 $titleObj = $rev->getTitle();
1457 $title = $titleObj->getPrefixedDBkey();
1458 $this->output( "$title..." );
1459 # Update searchindex
1460 $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1462 $this->output( "\n" );
1469 * Count down from $seconds to zero on the terminal, with a one-second pause
1470 * between showing each number. If the maintenance script is in quiet mode,
1471 * this function does nothing.
1475 * @codeCoverageIgnore
1476 * @param int $seconds
1478 protected function countDown( $seconds ) {
1479 if ( $this->isQuiet() ) {
1482 for ( $i = $seconds; $i >= 0; $i-- ) {
1483 if ( $i != $seconds ) {
1484 $this->output( str_repeat( "\x08", strlen( $i +
1 ) ) );
1486 $this->output( $i );
1491 $this->output( "\n" );
1495 * Wrapper for posix_isatty()
1496 * We default as considering stdin a tty (for nice readline methods)
1497 * but treating stout as not a tty to avoid color codes
1499 * @param mixed $fd File descriptor
1502 public static function posix_isatty( $fd ) {
1503 if ( !function_exists( 'posix_isatty' ) ) {
1506 return posix_isatty( $fd );
1511 * Prompt the console for input
1512 * @param string $prompt What to begin the line with, like '> '
1513 * @return string Response
1515 public static function readconsole( $prompt = '> ' ) {
1516 static $isatty = null;
1517 if ( is_null( $isatty ) ) {
1518 $isatty = self
::posix_isatty( 0 /*STDIN*/ );
1521 if ( $isatty && function_exists( 'readline' ) ) {
1522 return readline( $prompt );
1525 $st = self
::readlineEmulation( $prompt );
1527 if ( feof( STDIN
) ) {
1530 $st = fgets( STDIN
, 1024 );
1533 if ( $st === false ) {
1536 $resp = trim( $st );
1543 * Emulate readline()
1544 * @param string $prompt What to begin the line with, like '> '
1547 private static function readlineEmulation( $prompt ) {
1548 $bash = ExecutableFinder
::findInDefaultPaths( 'bash' );
1549 if ( !wfIsWindows() && $bash ) {
1551 $encPrompt = wfEscapeShellArg( $prompt );
1552 $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1553 $encCommand = wfEscapeShellArg( $command );
1554 $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1556 if ( $retval == 0 ) {
1558 } elseif ( $retval == 127 ) {
1559 // Couldn't execute bash even though we thought we saw it.
1560 // Shell probably spit out an error message, sorry :(
1561 // Fall through to fgets()...
1568 // Fallback... we'll have no editing controls, EWWW
1569 if ( feof( STDIN
) ) {
1574 return fgets( STDIN
, 1024 );
1578 * Get the terminal size as a two-element array where the first element
1579 * is the width (number of columns) and the second element is the height
1584 public static function getTermSize() {
1585 $default = [ 80, 50 ];
1586 if ( wfIsWindows() ) {
1589 // It's possible to get the screen size with VT-100 terminal escapes,
1590 // but reading the responses is not possible without setting raw mode
1591 // (unless you want to require the user to press enter), and that
1592 // requires an ioctl(), which we can't do. So we have to shell out to
1593 // something that can do the relevant syscalls. There are a few
1594 // options. Linux and Mac OS X both have "stty size" which does the
1596 $result = Shell
::command( 'stty', 'size' )
1598 if ( $result->getExitCode() !== 0 ) {
1601 if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1604 return [ intval( $m[2] ), intval( $m[1] ) ];
1608 * Call this to set up the autoloader to allow classes to be used from the
1611 public static function requireTestsAutoloader() {
1612 require_once __DIR__
. '/../tests/common/TestsAutoLoader.php';
1617 * Fake maintenance wrapper, mostly used for the web installer/updater
1619 class FakeMaintenance
extends Maintenance
{
1620 protected $mSelf = "FakeMaintenanceScript";
1622 public function execute() {
1628 * Class for scripts that perform database maintenance and want to log the
1629 * update in `updatelog` so we can later skip it
1631 abstract class LoggedUpdateMaintenance
extends Maintenance
{
1632 public function __construct() {
1633 parent
::__construct();
1634 $this->addOption( 'force', 'Run the update even if it was completed already' );
1635 $this->setBatchSize( 200 );
1638 public function execute() {
1639 $db = $this->getDB( DB_MASTER
);
1640 $key = $this->getUpdateKey();
1642 if ( !$this->hasOption( 'force' )
1643 && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__
)
1645 $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1650 if ( !$this->doDBUpdates() ) {
1654 if ( $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__
, 'IGNORE' ) ) {
1657 $this->output( $this->updatelogFailedMessage() . "\n" );
1664 * Message to show that the update was done already and was just skipped
1667 protected function updateSkippedMessage() {
1668 $key = $this->getUpdateKey();
1670 return "Update '{$key}' already logged as completed.";
1674 * Message to show that the update log was unable to log the completion of this update
1677 protected function updatelogFailedMessage() {
1678 $key = $this->getUpdateKey();
1680 return "Unable to log update '{$key}' as completed.";
1684 * Do the actual work. All child classes will need to implement this.
1685 * Return true to log the update as done or false (usually on failure).
1688 abstract protected function doDBUpdates();
1691 * Get the update key name to go in the update log table
1694 abstract protected function getUpdateKey();